package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import models.ItemModel;
import system.View;

public class ItemController extends AbstractMenuItemController
{	
	private ItemModel item = new ItemModel();

	public ItemController(View v) 
	{ 	
		super(v);
		abstractModel = item;
		item.addExceptionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) 
	{	String actionCommand = e.getActionCommand();
		
		if (actionCommand.equals("Delete Item"))
			showDialogWindow( new DeleteTupleDialog(
					view, actionCommand, "Key", new String[]{ "Item UPC: "},
					this
			));
		else if (actionCommand.equals("Insert Item"))
			showDialogWindow( new InsertTupleDialog(
				view, actionCommand, "Item",
				new String[]{ 
					"UPC: ", "Title: ", "Type: ", "Category: ", "Company: ",
					"Year: ", "Selling Price: "
				}, this
			));
		else if(actionCommand.equals("Display Items"))
			show();
	}
	
	@Override
	public int validateInsert(Vector<String> s) 
	{	
		if(s.size() != 7) return VALIDATIONERROR;
	
		try 
		{	Integer upc;
			String title;
			String type;
			String category;
			String company;
			Integer year;
			Integer sellPrice;
			
			if(s.get(0).trim().length() != 0){
				upc = Integer.valueOf(s.get(0).trim());
			} else return VALIDATIONERROR;
			if(s.get(1).length() != 0)
				title = s.get(1).trim();
			else return VALIDATIONERROR;
			if(s.get(2).length() != 0)
				type = s.get(2).trim();			
			else return VALIDATIONERROR;
			if(s.get(3).length() != 0)
				category = s.get(3).trim();
			else return VALIDATIONERROR;
			if(s.get(4).length() != 0)
				company = s.get(4).trim();
			else return VALIDATIONERROR;
			if(s.get(5).length() != 0)
				year = Integer.valueOf(s.get(5).trim());
			else return VALIDATIONERROR;
			if(s.get(6).length() != 0)
				sellPrice = Integer.valueOf(s.get(6).trim());
			else return VALIDATIONERROR;
			
			view.updateStatusBar("Inserting Item...");

			if (
				item.insert(upc, title, type, category, 
				company, year, sellPrice)
			) return operationSuccess();
			else return operationFailure(); 
		}  catch (NumberFormatException ex) {	return VALIDATIONERROR; }
	}

	@Override
	public int validateDelete(Vector<String> s) 
	{	
		if(s.size() != 1)
		return VALIDATIONERROR;
	
		try {
			Integer upc;
			
			if(s.get(0).trim().length() != 0){
				upc = Integer.valueOf(s.get(0).trim());
			} else return VALIDATIONERROR;
		
			view.updateStatusBar("Deleting Item...");

			if (item.delete(upc)) return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex){ return VALIDATIONERROR; }
	}
}

